<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable style="width: 200px">
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="源家谱名称" prop="sourceFamilyName">
          <el-input
            v-model="queryParams.sourceFamilyName"
            placeholder="请输入源家谱名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="目标家谱名称" prop="targetFamilyName">
          <el-input
            v-model="queryParams.targetFamilyName"
            placeholder="请输入目标家谱名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="sourcePersonId" label="源成员ID" prop="sourcePersonId" min-width="100" align="center" />
        <el-table-column key="sourceFamilyId" label="源家谱ID" prop="sourceFamilyId" min-width="100" align="center" />
        <el-table-column key="sourceFamilyName" label="源家谱名称" prop="sourceFamilyName" min-width="120" align="center" />
        <el-table-column key="targetFamilyId" label="目标家谱ID" prop="targetFamilyId" min-width="100" align="center" />
        <el-table-column key="targetFamilyName" label="目标家谱名称" prop="targetFamilyName" min-width="120" align="center" />
        <el-table-column key="targetPersonId" label="目标成员ID" prop="targetPersonId" min-width="100" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column key="status" label="状态" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '0' || scope.row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === '1' || scope.row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === '2' || scope.row.status === 2" type="danger">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="auditRemark" label="审核备注" prop="auditRemark" min-width="150" align="center" />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '0' || scope.row.status === 0"
              type="primary"
              size="small"
              link
              @click="handleAudit(scope.row)"
            >
              <template #icon>
                <Check />
              </template>
              审核
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleViewDetail(scope.row)"
            >
              <template #icon>
                <View />
              </template>
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 审核操作弹窗 -->
    <el-dialog
      v-model="auditDialog.visible"
      :title="auditDialog.title"
      width="90%"
      @close="handleCloseDialog"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="源家谱">
          <span>{{ auditForm.sourceFamilyName }}</span>
        </el-form-item>
        <el-form-item label="目标家谱">
          <span>{{ auditForm.targetFamilyName }}</span>
        </el-form-item>
        
        <!-- 家谱树左右对比部分 -->
        <div class="family-tree-comparison">
          <!-- 源家谱树 -->
          <div class="family-tree-section">
            <div class="section-header">
              <h3>源家谱关系图</h3>
            </div>
            <div class="family-tree-container">
              <SimpleFamilyTreeS
                v-if="sourceFamilyTreeData"
                v-model="sourceFamilyTreeData"
                :current-user-id="currentMemberId"
                title="源家谱成员关系图"
                :readonly="true"
              />
              <div v-else class="empty-tree-message">暂无源家谱信息</div>
            </div>
          </div>

          <!-- 目标家谱树 -->
          <div class="family-tree-section">
            <div class="section-header">
              <h3>目标家谱关系图</h3>
            </div>
            <div class="family-tree-container">
              <SimpleFamilyTreeS
                v-if="targetFamilyTreeData"
                v-model="targetFamilyTreeData"
                :current-user-id="targetMemberId"
                title="目标家谱成员关系图"
                :readonly="true"
              />
              <div v-else class="empty-tree-message">暂无目标家谱信息</div>
            </div>
          </div>
        </div>
        
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="'1'">通过</el-radio>
            <el-radio :label="'2'">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核备注" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            placeholder="请输入审核备注"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-drawer
      v-model="detailDrawer.visible"
      title="关系详情"
      size="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="源成员ID">{{ detailData.sourcePersonId }}</el-descriptions-item>
        <el-descriptions-item label="源家谱ID">{{ detailData.sourceFamilyId }}</el-descriptions-item>
        <el-descriptions-item label="源家谱名称">{{ detailData.sourceFamilyName }}</el-descriptions-item>
        <el-descriptions-item label="目标家谱ID">{{ detailData.targetFamilyId }}</el-descriptions-item>
        <el-descriptions-item label="目标家谱名称">{{ detailData.targetFamilyName }}</el-descriptions-item>
        <el-descriptions-item label="目标成员ID">{{ detailData.targetPersonId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailData.status === '0' || detailData.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="detailData.status === '1' || detailData.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="detailData.status === '2' || detailData.status === 2" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核备注">{{ detailData.auditRemark }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Close, View, Search, Refresh } from '@element-plus/icons-vue'
import PersonAPI from "@/api/genealogy/person.api"
import SimpleFamilyTreeS from "@/components/FamilyTree/SimpleFamilyTreeS.vue"

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: '',
  sourceFamilyName: '',
  targetFamilyName: ''
})

// 表格数据
const loading = ref(false)
const total = ref(0)
const pageData = ref([])
const dataTableRef = ref()

// 家谱树相关变量
const sourceFamilyTreeData = ref(null)
const targetFamilyTreeData = ref(null)
const currentMemberId = ref('')
const targetMemberId = ref('')

// 审核弹窗
const auditDialog = reactive({
  visible: false,
  title: '审核申请'
})

const auditForm = reactive({
  id: null,
  sourceFamilyName: '',
  targetFamilyName: '',
  remark: '',
  status: '1'
})

const auditRules = {
  remark: [{ required: true, message: '请输入审核备注', trigger: 'blur' }]
}

const auditFormRef = ref()

// 详情抽屉
const detailDrawer = reactive({
  visible: false
})

const detailData = ref({})

// 初始化
onMounted(() => {
  handleQuery()
})

// 查询列表
const handleQuery = async () => {
  loading.value = true
  try {
    const res = await PersonAPI.getFamilyJoinList(queryParams)
    pageData.value = res.list
    total.value = res.total
  } catch (error) {
    console.error('获取家谱关系列表失败', error)
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleResetQuery = () => {
  Object.assign(queryParams, {
    status: '',
    sourceFamilyName: '',
    targetFamilyName: ''
  })
  handleQuery()
}

// 审核申请
const handleAudit = (row) => {
  auditDialog.title = '审核申请'
  Object.assign(auditForm, {
    id: row.id,
    sourceFamilyName: row.sourceFamilyName,
    targetFamilyName: row.targetFamilyName,
    remark: '',
    status: '1' // 默认选择通过
  })
  auditDialog.visible = true
  
  // 加载家谱树数据
  loadFamilyTreeData(row)
}

// 加载家谱树数据
const loadFamilyTreeData = async (row) => {
  loading.value = true
  try {
    // 加载源家谱树数据
    const sourceRes = await PersonAPI.getTreeDataForFour(row.sourcePersonId)
    console.log('获取到的源关系树数据:', sourceRes);
    sourceFamilyTreeData.value = sourceRes;
    
    // 设置当前成员ID
    currentMemberId.value = row.sourcePersonId
    
    // 加载目标家谱树数据
    const targetRes = await PersonAPI.getTreeDataForFour(row.targetPersonId)
    console.log('获取到的目标关系树数据:', targetRes);
    targetFamilyTreeData.value = targetRes;
    
    // 设置目标成员ID
    targetMemberId.value = row.targetPersonId
    
  } catch (error) {
    console.error('获取家谱树数据失败', error)
    ElMessage.error('获取家谱树数据失败')
    sourceFamilyTreeData.value = null
    targetFamilyTreeData.value = null
  } finally {
    loading.value = false
  }
}

// 提交审核
const submitAudit = async () => {
  auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await PersonAPI.auditFamilyJoin({
          id: auditForm.id,
          status: auditForm.status,
          remark: auditForm.remark,
          familyData: {
            sourceFamily: sourceFamilyTreeData.value,
            targetFamily: targetFamilyTreeData.value
          }
        })
        ElMessage.success(auditForm.status === '1' ? '已通过申请' : '已拒绝申请')
        auditDialog.visible = false
        handleQuery()
      } catch (error) {
        console.error('审核失败', error)
      }
    }
  })
}

// 关闭弹窗
const handleCloseDialog = () => {
  auditFormRef.value?.resetFields()
  sourceFamilyTreeData.value = null
  targetFamilyTreeData.value = null
  currentMemberId.value = ''
  targetMemberId.value = ''
}

// 查看详情
const handleViewDetail = (row) => {
  detailData.value = { ...row }
  detailDrawer.visible = true
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.family-tree-comparison {
  display: flex;
  flex-direction: row;
  gap: 20px;
  margin: 20px 0;
}

.family-tree-section {
  flex: 1;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 16px;
}

.family-tree-container {
  width: 100%;
  height: 400px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background-color: #fff;
  overflow: auto;
  padding: 10px;
}

.empty-tree-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.node-count {
  display: flex;
  align-items: center;
}

.node-count-badge {
  background-color: #409EFF;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}
</style>
